﻿param (
    [string]$addPath,
    [string]$rmPath,
    [string[]]$install,
    [string]$uninstall,
    [string]$setEnvKey,
    [string]$setEnvValue,
    [string]$rmEnvKey, # 新增参数：删除环境变量的键名
    [switch]$g,
    [switch]$h
)

# -----------------------------
# 多语言提示字典（支持统一管理和未来多语言）
# -----------------------------
$lang = @{
    HelpTitle           = "📚 使用说明：Windows 工具集 tool.ps1"
    Usage               = "用法: .\tool.ps1 [-addPath path] [-rmPath path] [-install path [alias]] [-uninstall alias] [-link target linkpath] [--help]"

    AddPathDesc         = "-addPath <路径>        添加路径到 PATH（默认用户，加 -g 表示系统）"
    RmPathDesc          = "-rmPath <路径>         从 PATH 中移除指定路径"
    InstallDesc         = "-install <路径> [别名] 创建快捷方式到【开始菜单】"
    AliasAuto           = "                        此操作不修改 PATH 环境变量"
    UninstallDesc       = "-uninstall <别名>      删除指定名称的快捷方式"
    GlobalSwitch        = "-g                    可选。表示操作【系统】PATH（需管理员权限）"
    HelpDesc            = "--help (-h)           显示此帮助信息并退出"

    ExampleTitle        = "示例："
    AddExample          = "  添加路径到用户 PATH:"
    AddGlobalExample    = "  添加路径到系统 PATH（需管理员权限）:"
    RmExample           = "  从 PATH 移除路径:"
    AutoAliasExample    = "  自动使用文件名作为别名（不修改 PATH）:"
    ManualAliasExample  = "  手动指定别名（不修改 PATH）:"
    UninstallExample    = "  卸载快捷方式:"
    HelpExample         = "  显示帮助信息:"

    PathAdded           = "✅ 已将 '{0}' 添加到 {1} 级别的 PATH 的最前面，并移除了旧版本。"
    PathRemoved         = "✅ 已从 {0} 级别的 PATH 中移除了 '{1}'"
    MissingParams       = "❌ 缺少必要参数，请查看帮助。"
    ExeNotFound         = "❌ 指定的可执行文件不存在: {0}"
    ShortcutCreated     = "✅ 已创建快捷方式: {0} -> `"{1}`""
    ShortcutRemoved     = "✅ 已删除快捷方式: {0}"
    ShortcutMissing     = "⚠️ 快捷方式不存在: {0}"
    CreateFailed        = "❌ 创建快捷方式失败: {0}"
    LinkSuccess         = "✅ 成功创建软链接: {0} -> {1}"
    LinkExists          = "⚠️ 链接路径已存在: {0}"
    LinkTargetMissing   = "❌ 目标路径不存在: {0}"
    AdminRequired       = "⚠️ 此功能需要以管理员身份运行此脚本。"
}

# -----------------------------
# 全局变量：开始菜单路径
# -----------------------------
$startMenuDir = "$env:APPDATA\Microsoft\Windows\Start Menu\Programs"

# -----------------------------
# 函数：显示帮助信息
# -----------------------------
function Show-Help {
    Write-Host "`n$($lang.HelpTitle)" -ForegroundColor Cyan
    Write-Host "-------------------------------------------------------------"
    Write-Host "$($lang.Usage)`n"

    Write-Host "参数说明：" -ForegroundColor Yellow
    Write-Host "  $($lang.AddPathDesc)"
    Write-Host "  $($lang.RmPathDesc)"
    Write-Host "  $($lang.InstallDesc)"
    Write-Host "  $($lang.AliasAuto)"
    Write-Host "  $($lang.UninstallDesc)"
    Write-Host "  $($lang.LinkDesc)"
    Write-Host "  $($lang.GlobalSwitch)"
    Write-Host "  $($lang.HelpDesc)`n"

    Write-Host "$($lang.ExampleTitle)" -ForegroundColor Yellow
    Write-Host "$($lang.AddExample)"
    Write-Host "    .\tool.ps1 -addPath `"D:\tools`""
    Write-Host "$($lang.AddGlobalExample)"
    Write-Host "    .\tool.ps1 -addPath `"D:\tools`" -g"
    Write-Host "$($lang.RmExample)"
    Write-Host "    .\tool.ps1 -rmPath `"D:\tools`""
    Write-Host "$($lang.AutoAliasExample)"
    Write-Host "    .\tool.ps1 -install `"D:\tools\java.exe`""
    Write-Host "$($lang.ManualAliasExample)"
    Write-Host "    .\tool.ps1 -install `"D:\tools\java.exe`" MyJava"
    Write-Host "$($lang.UninstallExample)"
    Write-Host "    .\tool.ps1 -uninstall Java"
    Write-Host "$($lang.LinkExample)"
    Write-Host "    .\tool.ps1 -link `"D:\data`" `"C:\link\data`""
    Write-Host "$($lang.HelpExample)"
    Write-Host "    .\tool.ps1 --help`n"
}

# -----------------------------
# 函数：获取默认别名（基于文件名）
# -----------------------------
function Get-DefaultAlias([string]$filePath) {
    $file = Split-Path -Leaf -Path $filePath
    return [System.IO.Path]::GetFileNameWithoutExtension($file)
}

# -----------------------------
# 函数：创建快捷方式
# -----------------------------
function New-Shortcut([string]$exePath, [string]$aliasName) {
    # 检查主文件是否存在
    $exeFile = $exePath.Split(' ', 2)[0].Trim('"')
    if (-not (Test-Path $exeFile -PathType Leaf)) {
        Write-Host ($lang.ExeNotFound -f $exeFile) -ForegroundColor Red
        return $false
    }

    # 确保目录存在
    if (-not (Test-Path $startMenuDir)) {
        New-Item -ItemType Directory -Path $startMenuDir -Force | Out-Null
    }

    $shortcutPath = "$startMenuDir\$aliasName.lnk"

    try {
        $WshShell = New-Object -ComObject WScript.Shell
        $shortcut = $WshShell.CreateShortcut($shortcutPath)
        $shortcut.TargetPath = $exeFile

        # 提取参数部分
        $arguments = $exePath.Substring($exeFile.Length).Trim()
        if ($arguments) {
            $shortcut.Arguments = $arguments
        }

        $shortcut.WorkingDirectory = Split-Path $exeFile
        $shortcut.IconLocation = $exeFile
        $shortcut.Save()

        Write-Host ($lang.ShortcutCreated -f $aliasName, $exePath) -ForegroundColor Green
        return $true
    } catch {
        Write-Host ($lang.CreateFailed -f $_) -ForegroundColor Red
        return $false
    }
}

# -----------------------------
# 函数：删除快捷方式
# -----------------------------
function Remove-Shortcut([string]$aliasName) {
    $shortcutPath = "$startMenuDir\$aliasName.lnk"
    if (Test-Path $shortcutPath) {
        Remove-Item -Path $shortcutPath -Force
        Write-Host ($lang.ShortcutRemoved -f $aliasName) -ForegroundColor Green
        return $true
    } else {
        Write-Host ($lang.ShortcutMissing -f $aliasName) -ForegroundColor Yellow
        return $false
    }
}

# -----------------------------
# 函数：添加路径到 PATH
# -----------------------------
function Add-PathToEnv([string]$path, [switch]$globalScope) {
    $target = if ($globalScope) { "Machine" } else { "User" }
    $OriginalPath = [Environment]::GetEnvironmentVariable("PATH", $target)
    $UpdatedPath = $OriginalPath.Replace(";$path", "").Replace("$path;", "")
    $UpdatedPath = $UpdatedPath.Trim().Trim(";")
    if ([string]::IsNullOrWhiteSpace($UpdatedPath)) {
        $UpdatedPath = $path
    } else {
        $UpdatedPath = "$path;$UpdatedPath"
    }
    [Environment]::SetEnvironmentVariable("PATH", $UpdatedPath, $target)
    $scopeText = if ($globalScope) { "系统 (Machine)" } else { "用户 (User)" }
    Write-Host ($lang.PathAdded -f $path, $scopeText) -ForegroundColor Green
}

# -----------------------------
# 函数：从 PATH 中移除路径
# -----------------------------
function Remove-PathFromEnv([string]$path, [switch]$globalScope) {
    $target = if ($globalScope) { "Machine" } else { "User" }
    $OriginalPath = [Environment]::GetEnvironmentVariable("PATH", $target)
    $UpdatedPath = $OriginalPath.Replace(";$path", "").Replace("$path;", "")
    $UpdatedPath = $UpdatedPath.Trim().Trim(";")
    [Environment]::SetEnvironmentVariable("PATH", $UpdatedPath, $target)
    $scopeText = if ($globalScope) { "系统 (Machine)" } else { "用户 (User)" }
    Write-Host ($lang.PathRemoved -f $scopeText, $path) -ForegroundColor Green
}

# -----------------------------
# 函数：删除环境变量
# -----------------------------
function Remove-EnvironmentVariable([string]$key, [switch]$globalScope) {
    $target = if ($globalScope) { "Machine" } else { "User" }
    if ([Environment]::GetEnvironmentVariable($key, $target)) {
        [Environment]::SetEnvironmentVariable($key, $null, $target)
        $scopeText = if ($globalScope) { "系统 (Machine)" } else { "用户 (User)" }
        Write-Host "✅ 已删除环境变量 '$key' ($scopeText)" -ForegroundColor Green
    } else {
        Write-Host "⚠️ 环境变量 '$key' 不存在 ($scopeText)" -ForegroundColor Yellow
    }
}

# -----------------------------
# 主程序逻辑
# -----------------------------
if ($h -or $PSBoundParameters.ContainsKey('h')) {
    Show-Help
    exit 0
}

$anyAction = $false

# 添加 PATH
if ($PSBoundParameters.ContainsKey("addPath")) {
    if (Test-Path -Path $addPath -PathType Container) {
        Add-PathToEnv -path $addPath -globalScope:$g
        $anyAction = $true
    }
}

# 移除 PATH
if ($PSBoundParameters.ContainsKey("rmPath")) {
    Remove-PathFromEnv -path $rmPath -globalScope:$g
    $anyAction = $true
}

# 安装快捷方式
if ($install.Count -ge 1) {
    $exePath = $install[0]
    $aliasName = if ($install.Count -ge 2) { $install[1] } else { Get-DefaultAlias $exePath }
    if (Test-Path -Path $exePath -PathType Leaf) {
        New-Shortcut -exePath $exePath -aliasName $aliasName
        $anyAction = $true
    } else {
        Write-Host "❌ 指定的可执行文件不存在: $exePath" -ForegroundColor Red
        $anyAction = $true
    }
}

# 卸载快捷方式
if ($uninstall) {
    Remove-Shortcut -aliasName $uninstall
    $anyAction = $true
}

# 设置环境变量
if ($PSBoundParameters.ContainsKey("setEnvKey") -and $PSBoundParameters.ContainsKey("setEnvValue")) {
    $target = if ($g) { "Machine" } else { "User" }
    [Environment]::SetEnvironmentVariable($setEnvKey, $setEnvValue, $target)
    $scopeText = if ($g) { "系统 (Machine)" } else { "用户 (User)" }
    Write-Host "✅ 已设置环境变量 '$setEnvKey' 为 '$setEnvValue' ($scopeText)" -ForegroundColor Green
    $anyAction = $true
}

# 删除环境变量
if ($PSBoundParameters.ContainsKey("rmEnvKey")) {
    Remove-EnvironmentVariable -key $rmEnvKey -globalScope:$g
    $anyAction = $true
}

# 如果没有任何操作
if (-not $anyAction) {
    Write-Host $lang.MissingParams -ForegroundColor Red
    Show-Help
    exit 1
}



